package ranger
{   
    import flash.geom.Point;
    
    import feathers.controls.Button;
    import feathers.themes.AeonDesktopTheme;
    import feathers.themes.MetalWorksMobileTheme;
    
    import ranger.clips.Clip;
    import ranger.clips.EnemyShip;
    import ranger.clips.LargeAsteroid;
    import ranger.clips.MediumAsteroid;
    import ranger.clips.PlayerShip;
    import ranger.clips.SmallAsteroid;
    
    import starling.display.Sprite;
    import starling.events.Event;
    import starling.events.Touch;
    import starling.events.TouchEvent;
    
    public class RangerGame extends Sprite 
    {	
		public static const ASTEROID_BOOST:uint = 10;
		
		private static var _totalAsteriods:uint = 0;
		
        private var _playerShip:PlayerShip;
		private var _button:Button;
        
        public function RangerGame() 
        {
            addEventListener(Event.ADDED_TO_STAGE, onAdded); 
        }
		
        private function onAdded(event:Event):void 
        {
			// load a feathers theme
			// new MetalWorksMobileTheme();
			new AeonDesktopTheme();
			
			// override the stage color to black
			stage.color = 0x000000;
			
			addAsteroids();
            addChild(new EnemyShip());
            _playerShip = new PlayerShip();
            addChild(_playerShip);
            
			// create a button and give it some text to display.
			var padding:Number = 10;
			_button = new Button();
			_button.label = "x" + ASTEROID_BOOST + " Asteroid!";
			_button.addEventListener(Event.TRIGGERED, onTriggerButton);
			addChild(_button);
			_button.validate();
			_button.x = stage.stageWidth - _button.width - padding;
			_button.y = stage.stageHeight - _button.height - padding;
			
            stage.addEventListener(TouchEvent.TOUCH, onTouch);
        }
		
		private function addAsteroids():void
		{
			trace("Adding " + ASTEROID_BOOST + " Asteroids");
			for (var i:uint = 0; i < ASTEROID_BOOST; ++i)
			{
				addRandomAsteroid();
			}
			
			_totalAsteriods += ASTEROID_BOOST;
			trace("Total asteroids " + _totalAsteriods);
			trace();
		}
		
		private function addRandomAsteroid():void
		{
			var random:Number = Clip.randomInt(0, 2);
			switch (random)
			{
				case 0:
                    addChild(new LargeAsteroid());
                    break;
				case 1:
                    addChild(new MediumAsteroid());
					break;
				case 2:
                    addChild(new SmallAsteroid());
					break;
			}
		}
		
		private function onTriggerButton(event:Event):void
		{
			addAsteroids();
		}
        
        private function onTouch(event:TouchEvent):void 
        {
            // get the mouse location related to the stage
            var touch:Touch = event.getTouch(stage);
 
			if (touch)
			{
				var point:Point = touch.getLocation(stage);
                _playerShip.driveTo(point);
			}
        }
    } 
}
